<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="billCode">
        <el-input
          v-model="queryParams.billCode"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单据名称" prop="billName">
        <el-input
          v-model="queryParams.billName"
          placeholder="请输入单据名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unitOfMeasure">
        <el-input
          v-model="queryParams.unitOfMeasure"
          placeholder="请输入单位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:assembly:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:assembly:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wm:assembly:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wm:assembly:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assemblyList" @selection-change="handleSelectionChange" border>
      <el-table-column label="序号" type="index" align="center" width="55"/>
      <el-table-column label="单据编号" align="center" prop="billCode" >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['wm:assembly:query']"
          >{{ scope.row.billCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="数量" align="center" prop="lineQuantity" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="图号" align="center" prop="drawNumber" />
      <el-table-column label="单据名称" align="center" prop="billName" />
      <el-table-column label="单据日期" align="center" prop="billDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.billDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="组装前物料仓库" align="center" prop="beforeWarehouse" />
<!--      <el-table-column label="组装钱物料仓库ids" align="center" prop="beforeWarehouseIds" />-->
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status=='已完成'" dffect="dark">已完成</el-tag>
          <el-tag type="info" v-if="scope.row.status=='草稿'" dffect="dark">草稿</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createByName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status == '草稿'"
            v-hasPermi="['wm:assembly:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="scope.row.status == '草稿'"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wm:assembly:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            v-if="scope.row.status == '已完成'"
            @click="handleView(scope.row)"
            v-hasPermi="['wm:assembly:query']"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改组装单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
        <el-form-item label="单据编号" prop="billCode">
          <el-input v-model="form.billCode" placeholder="请输入单据编号" :disabled="optType != 'add'"/>
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="单据名称" prop="billName">
          <el-input v-model="form.billName" placeholder="请输入单据名称" :disabled="optType == 'view'"/>
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="单据日期" prop="billDate">
          <el-date-picker clearable style="width: 100%"
                          :disabled="optType == 'view'"
            v-model="form.billDate"
            type="date"
            :default-value="new Date()"
            value-format="yyyy-MM-dd"
            placeholder="请选择单据日期">
          </el-date-picker>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
          <el-form-item label="组装前物料仓库" prop="beforeWarehouseIdList" label-width="130px">
            <!--          <el-input v-model="form.beforeWarehouse" placeholder="请输入组装钱物料仓库" />-->
            <el-select v-model="form.beforeWarehouseIdList" multiple clearable placeholder="请选择库区" :disabled="optType == 'view'"
                       @change="handleBeforWarehouseChange" style="width: 100%">
              <el-option
                          v-for="item in beforeWarehouseList"
                          :key="item.warehouseId"
                          :label="item.warehouseName"
                          :value="item.warehouseId">
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
        </el-row>
      </el-form>

<!--      <el-card shadow="always"  class="box-card">-->

        <AssemblyLine ref="assemlyline" v-if="form.billCode" :opt-type="optType" :assemblyId="form.id" :beforsWarehouseIds="form.beforeWarehouseIds"></AssemblyLine>
<!--      </el-card>-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tijiao" v-if="optType != 'view'">提 交</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAssembly,getAssembly,execute, delAssembly, addAssembly, updateAssembly,addAll,updateAll,getList } from "@/api/mes/wm/assembly";
import AssemblyLine from "@/views/mes/wm/assembly/line.vue"
import {getWarehouseList} from "@/api/mes/wm/warehouse";
import {genCode} from "@/api/system/autocode/rule";
import {getTransferclient} from "@/api/mes/wm/transferclient";
export default {
  name: "Assembly",
  components:{AssemblyLine},
  data() {
    return {

      beforeWarehouseList:[],
      optType:undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 组装单表格数据
      assemblyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        billCode: null,
        billName: null,
        billDate: null,
        beforeWarehouse: null,
        beforeWarehouseIds: null,
        status: null,
        createByName: null,
        itemCode: null,        itemName: null,
        specification: null,        unitOfMeasure: null, batchCode:null},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billCode: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
        billDate: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
        billName: [
          { required: true, message: "单据名称不能为空", trigger: "blur" }
        ],
        beforeWarehouseIdList: [
          { required: true, message: "组装前物料仓库不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouse()
  },
  methods: {
    /** 查询组装单列表 */
    getList() {
      this.loading = true;
      getList(this.queryParams).then(response => {
        this.assemblyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    //获取仓库
    getWarehouse(){
      this.beforeWarehouseList=[]
      getWarehouseList().then(response => {
        this.beforeWarehouseList = response.data.filter((el) =>{
          return el.warehouseCode.indexOf('VIR') == -1;
        })
      });

    },
    handleBeforWarehouseChange(value){
      console.log("3333333333333333333",this.form.beforeWarehouseIdList)
      const selectedLabels = this.beforeWarehouseList.filter(item => value.includes(item.warehouseId)).map(item => item.warehouseName);
      this.form.beforeWarehouse=selectedLabels.join(",")
      this.form.beforeWarehouseIds=value.join(",")
      console.log("11111",this.form.beforeWarehouse)
      console.log("2222222",this.form.beforeWarehouseIds)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        billCode: null,        billName: null,        billDate: new Date().toISOString().split('T')[0],
        beforeWarehouse: null,        beforeWarehouseIds: null,        status: "草稿",        createBy: null,
        createByName: null,        createTime: null,        updateBy: null,        updateTime: null,        tenantId: null
        ,beforeWarehouseIdList:[]};
      this.resetForm("form");
      this.form.assemblylineList=[]
      this.form.beforeLineList=[]

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('ASSEMBLY_CODE').then(response =>{
        this.form.billCode = response;
        this.open = true;
        this.optType="add"
        this.title = "添加组装单";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        getAssembly(id).then(response => {
          this.form = response.data;
          //不转换类型  出来的就是['2','3'] 是字符串的数组
          const ids=response.data.beforeWarehouseIds.split(",").map(Number)
          this.form.beforeWarehouseIdList=ids
          console.log("uuuuu",this.form.beforeWarehouseIdList)
          this.open = true;
          this.optType="update"
          this.title = "修改组装单";
        });

    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      const id = row.id || this.ids
      getAssembly(id).then(response => {
        this.form = response.data;
        //不转换类型  出来的就是['2','3'] 是字符串的数组
        const ids=response.data.beforeWarehouseIds.split(",").map(Number)
        this.form.beforeWarehouseIdList=ids
        this.open = true;
        this.optType="view"
        this.title = "查看组装单";
      });
    },
    // 执行
     tijiao() {
       // 可能 不保存，新建玩以后直接提交  或者修改后不保存直接提交  所以将submit一下
       this.$refs["form"].validate(valid => {
         if (valid) {
           const afterline = this.$refs.assemlyline.assemblylineList;
           const beforeline = this.$refs.assemlyline.beforeLineList;
           this.form.assemblylineList=afterline
           this.form.beforeLineList=beforeline

           if(!this.form.beforeWarehouseIds){
             this.$modal.msgWarning("组装前物料仓库不能为空");
           }
           //后产品 仓库库区库位不能为空
           for (let i = 0; i < afterline.length; i++) {
             if(afterline[i].warehouseId && afterline[i].locationId && afterline[i].areaId){
             }else{
               this.$modal.msgWarning("组装后产品仓库信息不能为空");
               return
             }
             if('Y' == afterline[i].enableMultiUnit) {
               if ((!afterline[i].storageUnitQuantity) || afterline[i].storageUnitQuantity == 0) {
                 this.$modal.msgWarning("组装前物料 " + afterline[i].itemCode + "的辅数量不能为空");
                 return;
               }
             }
           }
           // 组装前物料  开启多单位  辅数量不能为空
           for (let i = 0; i < beforeline.length; i++) {
             if('Y' == beforeline[i].enableMultiUnit){
               if((!beforeline[i].storageUnitQuantity) || beforeline[i].storageUnitQuantity == 0 ){
                 this.$modal.msgWarning("组装前物料 "+beforeline[i].itemCode+"的辅数量不能为空");
                 return;
               }

             }
           }

           if (this.form.id != null) {
             updateAll(this.form).then(response => {
               if(response.code == 200){
                 //生成出入库  并执行出入库
                 execute(this.form.id).then(response =>{
                   this.$modal.msgSuccess("提交成功");
                   this.open = false;
                   this.getList();
                 })
               }

             });
           } else {
             addAll(this.form).then(response => {
               if(response.code == 200){
                 //生成出入库  并执行出入库  addAll返回的事新增的单据头的id
                 execute(response.data).then(response =>{
                   this.$modal.msgSuccess("提交成功");
                   this.open = false;
                   this.getList();
                 })
               }
               this.open = false;
               this.getList();
             });
           }
         }
       });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const afterline = this.$refs.assemlyline.assemblylineList;
          const beforeline = this.$refs.assemlyline.beforeLineList;
          this.form.assemblylineList=afterline
          this.form.beforeLineList=beforeline
         if((!afterline) && afterline.length == 1){
           this.$modal.msgWarning("组装后产品只能为单条数据，否则无法保存");
         }
          if(!this.form.beforeWarehouseIds){
            this.$modal.msgWarning("组装前物料仓库不能为空");
            return;
          }

          //后产品 仓库库区库位不能为空
          for (let i = 0; i < afterline.length; i++) {
            if(afterline[i].warehouseId && afterline[i].locationId && afterline[i].areaId){
            }else{
              this.$modal.msgWarning("组装后产品仓库信息不能为空");
              return
            }
            if('Y' == afterline[i].enableMultiUnit) {
              if ((!afterline[i].storageUnitQuantity) || afterline[i].storageUnitQuantity == 0) {
                this.$modal.msgWarning("组装前物料 " + afterline[i].itemCode + "的辅数量不能为空");
                return;
              }
            }

          }
          // 组装前物料  开启多单位  辅数量不能为空
          for (let i = 0; i < beforeline.length; i++) {
            if('Y' == beforeline[i].enableMultiUnit){
              if((!beforeline[i].storageUnitQuantity) || beforeline[i].storageUnitQuantity == 0 ){
                this.$modal.msgWarning("组装前物料 "+beforeline[i].itemCode+"的辅数量不能为空");
                return;
              }
            }
            if((!beforeline[i].lineQuantity) || beforeline[i].lineQuantity <= 0){
              this.$modal.msgWarning("组装前物料 "+beforeline[i].itemCode+"的数量必须大于0");
              return;
            }
          }

          if (this.form.id != null) {
            updateAll(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAll(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮   改为这种Promise  因为提交的时候，先调用submit,先保存或者更新数据，等submit执行完成后，在执行出入库的动作*/
/*    submitForm() {
      return new Promise((resolve, reject) => {
        this.$refs["form"].validate(valid => {
          if (valid) {
            const afterline = this.$refs.assemlyline.assemblylineList;
            const beforeline = this.$refs.assemlyline.beforeLineList;
            this.form.assemblylineList = afterline;
            this.form.beforeline = afterline;

            const promise = this.form.id != null
                ? updateAll(this.form)
                : addAll(this.form);

            promise.then(response => {
              this.$modal.msgSuccess(this.form.id != null ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
              resolve(response);  // 提交成功时resolve
            }).catch(error => {
              reject(error);  // 提交失败时reject
            });
          }
          /!*else {
            reject(new Error("表单验证失败"));
          }*!/
        });
      });
    },*/
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除组装单编号为"' + ids + '"的数据项？').then(function() {
        return delAssembly(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/assembly/export', {
        ...this.queryParams
      }, `assembly_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
